package com.gxa.modules.service.accessservice.impl;

import com.gxa.common.R;
import com.gxa.modules.mapper.accessmapper.ResourceMapper;
import com.gxa.modules.pojo.AlarmRules;
import com.gxa.modules.pojo.Organizational;
import com.gxa.modules.pojo.Resource;
import com.gxa.modules.service.accessservice.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.util.ArrayList;
import java.util.List;


@Service
public class ResourceServiceImpl implements ResourceService {

    @Autowired
    private ResourceMapper resourceMapper;

    @Override
    public R selectResource(String resourceName, String resourceLevel,String page,String size) {
        R<Object> r = new R<>();
        int statrIndex=(Integer.parseInt(page)-1)*Integer.parseInt(size);
        int endIndex=Integer.parseInt(page)*Integer.parseInt(size);
        r.setCode(200);
        r.setMsg("查询成功！");
        List<Resource> list;
        if (resourceLevel != null || "".equals(resourceLevel)
                || resourceName != null || "".equals(resourceName)){
            list=resourceMapper.selectResource(resourceName, resourceLevel,statrIndex,endIndex);
        }else {
            list=resourceMapper.selectResource(resourceName, "1",statrIndex,endIndex);

            for (int i = 0; i < list.size(); i++) {
                long pids=list.get(i).getId();
                list.get(i).setNextPids(resourceMapper.selectResourceByPids(pids));
            }
        }
        r.setData(list);
        return r;
    }

    @Override
    public R insertResource(Resource resource) {
        R<Object> r = new R<>();

        r.setCode(500);
        r.setMsg("新增失败！");


        if (resourceMapper.insertResource(resource)>0){

            r.setCode(200);
            r.setMsg("新增成功！");
        }
        return r;
    }

    @Override
    public R deleteResource(String resourceId) {
        R<Object> r = new R<>();

        if ( resourceId ==null || "".equals(resourceId) ){
            r.setCode(500);
            r.setMsg("请选择要删除的信息！");
            return r;
        }

        r.setCode(500);
        r.setMsg("删除失败！");

        String[] strings = resourceId.split(",");
        for (int i=0;i<strings.length;i++) {
            resourceId=strings[i];
            if(resourceMapper.deleteResource(resourceId)>0){

                resourceMapper.deletePermissions(resourceId);
                r.setCode(200);
                r.setMsg("删除成功！");
            }
        }


        return r;
    }

    @Override
    public R updateResource(Resource resource) {
        R<Object> r = new R<>();

        r.setCode(500);
        r.setMsg("修改失败！");

        if (resourceMapper.updateResource(resource)>0){
            r.setCode(200);
            r.setMsg("修改成功！");
        }
        return r;
    }
}
